<template>
  <div class="add-schedule">
    <div class="title">
      {{$t('channelsettings.schedule7')}}<br/>
      {{$t('channelsettings.schedulea23')}}<br/>
      {{$t('channelsettings.schedulea22')}}<br/>
      {{$t('channelsettings.schedule8')}}<br/>
      {{$t('channelsettings.schedule9')}}<br/>
      {{$t('channelsettings.schedule10')}}
    </div>
    <el-form label-position="top" :model="serviceObj" class="demo-form-stacked" ref="serviceObj" :rules="rules" v-if="reload">
      <el-row :gutter="20" class="mar-t-10">
        <el-col :span="9">
          <el-form-item prop="DisplayName" :label="$t('channelsettings.schedule11')">
            <el-input v-model.trim="serviceObj.DisplayName" :placeholder="$t('channelsettings.schedule12')" style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item prop="Order" :label="$t('channelsettings.schedule4')">
            <el-input v-model="serviceObj.Order" :placeholder="$t('channelsettings.schedule13')" style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="mar-t-10">
        <el-form-item :label="$t('report.particularyear')" style="padding-left: 10px" v-if="isShowYear">
          <el-col :span="9" style="padding-left: 0px">
            <el-form-item prop="StartDate">
              <el-input v-model.trim="serviceObj.YearStartDate" placeholder="" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col class="bet" :span="2" style="padding-left: 6px">
          </el-col>
          <el-col :span="9">
            <el-form-item prop="EndDate">
              <el-input v-model.trim="serviceObj.YearEndDate" placeholder="" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
      </el-row>
      <el-row :gutter="20" class="mar-t-10">
        <el-form-item :label="$t('report.imReportDate')" style="padding-left: 10px">
          <el-col :span="9" style="padding-left: 0px">
            <el-form-item prop="StartDate">
              <el-input v-model.trim="serviceObj.StartDate" placeholder="" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col class="bet" :span="2" style="padding-left: 6px">
          </el-col>
          <el-col :span="9">
            <el-form-item prop="EndDate">
              <el-input v-model.trim="serviceObj.EndDate" placeholder="" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
      </el-row>
      <el-row :gutter="20" class="mar-t-10">
        <el-form-item :label="$t('sms.time')" style="padding-left: 10px">
          <el-col :span="9" style="padding-left: 0px">
            <el-form-item prop="StartTime">
              <el-input v-model.trim="serviceObj.StartTime" placeholder="" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col class="bet" :span="2" style="padding-left: 6px">
          </el-col>
          <el-col :span="9">
            <el-form-item prop="EndTime">
              <el-input v-model.trim="serviceObj.EndTime" placeholder="" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
      </el-row>
    </el-form>
    <div class="schedule-week ismemory mar-t-10">
      <div class="skill-name pb20">
        <p style="margin-bottom:5px;">{{$t('channelsettings.schedule14')}}</p>
        <el-checkbox v-model="serviceObj.WeekMon">{{$t('channelsettings.schedule15')}}</el-checkbox>
        <el-checkbox v-model="serviceObj.WeekTue">{{$t('channelsettings.schedule16')}}</el-checkbox>
        <el-checkbox v-model="serviceObj.WeekWed">{{$t('channelsettings.schedule17')}}</el-checkbox>
        <el-checkbox v-model="serviceObj.WeekThu">{{$t('channelsettings.schedule18')}}</el-checkbox>
        <el-checkbox v-model="serviceObj.WeekFri">{{$t('channelsettings.schedule19')}}</el-checkbox>
        <el-checkbox v-model="serviceObj.WeekSat">{{$t('channelsettings.schedule20')}}</el-checkbox>
        <el-checkbox v-model="serviceObj.WeekSun">{{$t('channelsettings.schedule21')}}</el-checkbox>
      </div>
    </div>
    <div class="schedule-proid ismemory">
      <div class="assign-rule pb20">
        <p style="margin-bottom:5px;">{{$t('channelsettings.serviceNumber9')}}</p>
        <el-select size="mini" v-model="serviceObj.IvrProcessId" :placeholder="$t('public.pleasePick')" @change="ToChangePeerId" filterable>
          <el-option
            :label="$t('channelsettings.serviceNumber10')"
            value="">
          </el-option>
          <el-option
            v-for="(item, index) in toPeerIdArr"
            :key="index"
            :label="item.DisplayName"
            :value="item._id">
          </el-option>
        </el-select>
      </div>
    </div>
    <div class="schedule-peer ismemory">
      <div class="assign-rule pb20">
        <p style="margin-bottom:5px;">{{$t('channelsettings.serviceNumber11')}}</p>
        <el-select size="mini" v-model="serviceObj.ToPeerType" :placeholder="$t('public.pleasePick')" style="padding-right: 33px" @change="ToChangePeer" :disabled="flagPerr" filterable>
          <el-option
            v-for="(item, index) in toPeerTypeArr"
            :key="index"
            :label="item.TypeName"
            :value="item.TypeValue">
          </el-option>
        </el-select>
        <el-select size="mini" v-model="serviceObj.ToPeer" filterable :placeholder="$t('public.pleasePick')" :disabled="flagPerr">
          <el-option
            v-for="(item, index) in systemPeerTypeArr"
            :key="index"
            :label="item.name"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
    </div>
    <div style="clear: both">
      <el-button type="primary" @click="submit()" class='primary_btn'>{{$t('public.save')}}</el-button>
    </div>
  </div>
</template>
<script>
  import {deepClone} from '@/utils/m7Utils'
  import {checkform} from '@/utils/validate'
  export default {
    name: 'editSchedule',
    data () {
      var validateOptName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(this.$t('validate.required')))
        } else if (checkform(value, 'Number')) {
          callback(new Error(this.$t('channelsettings.schedule28')))
        } else if (value < 1 || value > 999) {
          callback(new Error(this.$t('channelsettings.schedule28')))
        } else {
          callback()
        }
      }
      let datePattern = new RegExp(/^([1-9]|[1][012])-([1-9]|[12][0-9]|[3][01])$/)
      var validateStartDate = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(this.$t('validate.required')))
        } else if (!datePattern.test(value) && value !== '*') {
          callback(new Error('请输入正确的开始日期！'))
        } else {
          callback()
        }
      }
      var validateEndDate = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(this.$t('validate.required')))
        } else if (!datePattern.test(value) && value !== '*') {
          callback(new Error('请输入正确的结束日期！'))
        } else {
          callback()
        }
      }
      let timePattern = new RegExp(/^([01][0-9]|[2][0-3]):[0-5][0-9]$/)
      var validateStartTime = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(this.$t('validate.required')))
        } else if (!timePattern.test(value) && value !== '*') {
          callback(new Error('请输入正确的开始时间！'))
        } else {
          callback()
        }
      }
      var validateEndTime = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(this.$t('validate.required')))
        } else if (!timePattern.test(value) && value !== '*') {
          callback(new Error('请输入正确的结束时间！'))
        } else if (value !== '*') {
          let lastNum = value.substring(value.length - 1)
          if (lastNum % 2 === 0) {
            callback(new Error('设置日程结束时间，请将分钟设置为奇数，如18:59，即19点之前！'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return {
        rules: {
          DisplayName: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ],
          Order: [
            {required: true, validator: validateOptName, trigger: 'blur'}
          ],
          StartDate: [
            {required: true, validator: validateStartDate, trigger: 'blur'}
          ],
          EndDate: [
            {required: true, validator: validateEndDate, trigger: 'blur'}
          ],
          StartTime: [
            {required: true, validator: validateStartTime, trigger: 'blur'}
          ],
          EndTime: [
            {required: true, validator: validateEndTime, trigger: 'blur'}
          ]
        },
        flagPerr: false,
        toPeerIdArr: [],
        toPeerTypeArr: [
          {TypeValue: 'system', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup53')},
          {TypeValue: 'ivr_node_queue', TypeName: this.$t('public.queues')},
          {TypeValue: 'account_user', TypeName: this.$t('public.agent')},
          {TypeValue: 'ivr_node_announcement', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup54')},
          {TypeValue: 'ivr_node_text_announcement', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup55')},
          {TypeValue: 'ivr_node_ivr', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup56')},
          {TypeValue: 'ivr_node_encrypt_md5', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup57')},
          {TypeValue: 'ivr_node_validation', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup58')},
          {TypeValue: 'ivr_node_assignment', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup59')},
          {TypeValue: 'ivr_node_route', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup60')},
          {TypeValue: 'ivr_node_ivr_menu', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup61')},
          {TypeValue: 'ivr_node_call_url', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup62')},
          {TypeValue: 'ivr_node_date', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup63')},
          {TypeValue: 'ivr_node_twowaycall', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup64')},
          {TypeValue: 'ivr_node_asr', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup65')},
          {TypeValue: 'ivr_node_voice_mail', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup66')},
          {TypeValue: 'ivr_node_room', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup67')},
          {TypeValue: 'ivr_node_satisfaction', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup68')},
          {TypeValue: 'ivr_node_superDialJobNum', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup69')},
          {TypeValue: 'ivr_node_extension_peer', TypeName: this.$t('callServiceSkillGroup.callServiceSkillGroup70')}
        ],
        systemPeerTypeArr: [],
        systemPeerTypeArr1: [
          {name: this.$t('softPhoneBar.hangup'), value: '0'},
          {name: this.$t('cti.satiSearch'), value: '1'},
          {name: this.$t('call.dialNumber'), value: '2'}
        ],
        toPeerArr: [],
        serviceObj: {},
        reload: false,
        isShowYear: false
      }
    },
    props: {
      tableData: {
        type: Object,
        default: {}
      },
      editScheduleInfo: {}
    },
    methods: {
//      改变流程 修改流转到的数据
      ToChangePeerId (val) {
        if (val) {
          this.flagPerr = true
          this.toPeerIdArr.forEach(item => {
            if (item._id === val) {
              this.systemPeerTypeArr = []
              this.flowOptionsChange(item.FirstNodeType, this.systemPeerTypeArr)
              this.serviceObj.ToPeer = item.FirstNode
              this.serviceObj.ToPeerType = item.FirstNodeType
            }
          })
        } else {
//          流程到是否可点击
          this.flagPerr = false
          this.serviceObj.IvrProcessId = ''
          this.serviceObj.ToPeerType = this.toPeerTypeArr[0].TypeValue
          this.systemPeerTypeArr = this.systemPeerTypeArr1
          this.serviceObj.ToPeer = this.systemPeerTypeArr[0].value
        }
      },
      flowOptionsChange (val, options) {
        let toPeerArr = this.$store.state.session.ivrMap[this.serviceObj.PBX].data[val]
        if (!val || val === 'system') {
          this.systemPeerTypeArr1.forEach(item => {
            options.push({name: item.name, value: item.value})
          })
        } else {
          options.push({name: this.$t('public.pleasePick1'), value: ''})
          if (toPeerArr) {
            if (val === 'account_user') {
              toPeerArr.forEach(item => {
                options.push({name: item.displayName, value: item._id})
              })
            } else {
              toPeerArr.forEach(item => {
                options.push({name: item.DisplayName, value: item.Exten})
              })
            }
          }
        }
      },
//      改变流转到数据
      ToChangePeer (val) {
        this.systemPeerTypeArr = []
        if (val === 'system') {
          this.systemPeerTypeArr = this.systemPeerTypeArr1
          this.serviceObj.ToPeer = this.systemPeerTypeArr[0].value
        } else {
          this.flowOptionsChange(val, this.systemPeerTypeArr)
          let array = this.systemPeerTypeArr.filter((item) => {
            return item.value === this.serviceObj.ToPeer
          })
          if (array.length === 0) {
            this.serviceObj.ToPeer = this.systemPeerTypeArr[0].value
          }
        }
//        this.systemPeerTypeArr = []
//        if (val === 'system') {
//          this.systemPeerTypeArr = this.systemPeerTypeArr1
//          this.serviceObj.ToPeer = this.systemPeerTypeArr[0].value
//        } else {
//          this.flowOptionsChange(val, this.systemPeerTypeArr)
//          if (val === this.serviceObj.ToPeerType) {
//            if ((this.serviceObj.ToPeer !== '0') && (this.serviceObj.IvrProcessId !== '')) {
//              this.serviceObj.ToPeer = this.serviceObj.ToPeer
//            } else {
//              this.serviceObj.ToPeer = this.systemPeerTypeArr[0].value
//            }
//          }
//        }
      },
//    初始化流程 toPeerIdArr
      handlePerrIdData () {
        let arr = this.$store.state.session.ivrMap[this.serviceObj.PBX].data.ivr_process
        if (arr.length !== 0) {
          arr.forEach(item => {
            let obj = {
              FirstNode: item.FirstNode,
              FirstNodeType: item.FirstNodeType,
              _id: item._id,
              DisplayName: item.DisplayName
            }
            this.toPeerTypeArr.forEach(item1 => {
              if (item1.TypeValue === item.FirstNodeType) {
                obj.DisplayName = obj.DisplayName + '(' + item1.TypeName
              }
            })
            let toPeerArr = this.$store.state.session.ivrMap[this.serviceObj.PBX].data[item.FirstNodeType]
            toPeerArr.forEach(item2 => {
              if (item.FirstNodeType === 'account_user') {
                if (item2._id === item.FirstNode) {
                  obj.DisplayName = obj.DisplayName + ' - ' + item2.displayName + ')'
                }
              } else {
                if (item2.Exten === item.FirstNode) {
                  obj.DisplayName = obj.DisplayName + ' - ' + item2.DisplayName + ')'
                }
              }
            })
            this.toPeerIdArr.push(obj)
          })
        } else {
          this.toPeerIdArr = []
        }
        if (this.serviceObj.IvrProcessId) {
          this.flagPerr = true
        }
      },
//      是添加还是修改 处理this.serviceObj的回显值
      changeData (_schedule) {
        console.log(_schedule)
        this.getIsShowYear(_schedule.PBX)
        this.serviceObj = {
          ServiceNo: _schedule.ServiceNo,
          DisplayName: _schedule.DisplayName,
          Order: _schedule.Order,
          StartDate: _schedule.StartDate,
          EndDate: _schedule.EndDate,
          StartTime: _schedule.StartTime,
          YearStartDate: _schedule.YearStartDate || '*',
          YearEndDate: _schedule.YearEndDate || '*',
          EndTime: _schedule.EndTime,
          WeekMon: _schedule.WeekMon,
          WeekTue: _schedule.WeekTue,
          WeekWed: _schedule.WeekWed,
          WeekThu: _schedule.WeekThu,
          WeekFri: _schedule.WeekFri,
          WeekSat: _schedule.WeekSat,
          WeekSun: _schedule.WeekSun,
          ToPeerType: _schedule.ToPeerType,
          ToPeer: _schedule.ToPeer,
          IvrProcessId: _schedule.IvrProcessId || '',
          Account: _schedule.Account,
          PBX: _schedule.PBX,
          AnnouncementId: _schedule.AnnouncementId,
          _id: _schedule._id
        }
        this.toPeerIdArr = []
        this.handlePerrIdData()
      },
      compareDate (data) {
        const startMoth = parseInt(data.StartDate.split('-')[0])
        const startDay = parseInt(data.StartDate.split('-')[1])
        const endMonth = parseInt(data.EndDate.split('-')[0])
        const endDay = parseInt(data.EndDate.split('-')[1])
        if (startMoth > endMonth) {
          return false
        }
        if (startMoth === endMonth && startDay > endDay) {
          return false
        }
        return true
      },
      submit () {
        this.$refs.serviceObj.validate((valid) => {
          if (valid) {
            let nameFlag = false
            let orderFlag = false
            console.log(this.serviceObj)
            let _tableData = deepClone(this.tableData)
            console.log(_tableData)
            if (_tableData.SchedulesList) {
              _tableData.SchedulesList.forEach(item => {
                if ((this.serviceObj._id !== item._id) && (this.serviceObj.DisplayName === item.DisplayName)) {
                  nameFlag = true
                }
                if ((this.serviceObj._id !== item._id) && (parseInt(this.serviceObj.Order) === item.Order)) {
                  orderFlag = true
                }
              })
            }
            if (nameFlag) {
              this.$message.error(this.$t('channelsettings.schedule22'))
              return
            }
            if (orderFlag) {
              this.$message.error(this.$t('channelsettings.schedule23'))
              return
            }
            if (this.serviceObj.StartDate !== '*' && this.serviceObj.EndDate !== '*') {
              if (!this.compareDate(this.serviceObj)) {
                this.$message.error(this.$t('channelsettings.schedule24'))
                return
              }
            }
            if (!(this.serviceObj.WeekMon || this.serviceObj.WeekTue || this.serviceObj.WeekWed || this.serviceObj.WeekThu || this.serviceObj.WeekFri || this.serviceObj.WeekSat || this.serviceObj.WeekSun)) {
              this.$message.error(this.$t('channelsettings.schedule25'))
              return
            }
            this.serviceObj.Order = parseInt(this.serviceObj.Order)
            console.log(this.serviceObj)
            let _data = deepClone(this.serviceObj)
            if (_data.SchedulesList) {
              delete _data.SchedulesList
            }
            this.$store.dispatch('updateSchedule', _data).then(res => {
              if (res && res.success) {
                this.$message.success(this.$t('channelsettings.schedule26'))
                this.$emit('editRefresh', res.data ? res.data.ServiceNo : (res.list && res.list[0]) ? res.list[0].ServiceNo : '')
              } else {
                this.$message.error(this.$t('channelsettings.schedule27'))
              }
            })
          }
        })
      },
      getIsShowYear (pbx) {
        this.$store.dispatch('getNewFeaturesReport', {pbx: pbx}).then((res)=>{
          if (res && res.data && res.data.features && res.data.features.indexOf('YearAdd') > -1) {
            this.isShowYear = true
          } else {
            this.isShowYear = false
          }
        })
      }
    },
    watch: {
      editScheduleInfo () {
        this.reload = false
        this.$nextTick(() => {
          this.reload = true
          let _schedule = deepClone(this.editScheduleInfo)
          this.changeData(_schedule)
        })
      }
    },
    beforeMount () {
      this.reload = true
      let _schedule = deepClone(this.editScheduleInfo)
      console.log(_schedule)
//      this.systemPeerTypeArr = deepClone(this.systemPeerTypeArr1)
      this.changeData(_schedule)
      this.ToChangePeer(_schedule.ToPeerType)
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .mar-t-10
    margin-top 10px
  .bet
    &:before
      content: ''
      display inline-block
      width 15px
      height 1px
      margin 3px 12px
      background $cf-gray5
      text-align center
  .title
    color $c-prompt
    margin-bottom 10px
  .add-schedule
    padding 20px
    .el-input,.el-select
      width 220px
    .skill-name,.assign-rule
      float left
    .skill-name
      margin-right 30px
    .ismemory
      clear both
    .pb20
      padding-bottom 20px
    .icon-zuixiaohua
      font-size: 12px;
      color: #737373;
      padding: 0px 10px;
    .tishi
      color $c-prompt
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
</style>
